import { CodeGenerator } from "./CodeGenerator"
import { EjsCodeEncoder, EjsType } from "./EjsCodeEncoder"
import { OpenApi } from "./OpenApi"
import { ApplyMethodsParamItem, SinglePageVueCodeGeneratorInterface, SinglePageVueComponentInterface, VueComponent } from "./VueCodeGenerator"

export class EjsVueComponent extends VueComponent {
  ejsContent: string
  renderContent: string
  options: any
  ejsCodeEncoder: EjsCodeEncoder
  constructor(template: string, type: EjsType = EjsType.TEXT_CONTENT) {
    super({})
    this.ejsCodeEncoder = new EjsCodeEncoder(template, type)
  }

  async encode(codeGenerator: SinglePageVueCodeGeneratorInterface) {
    if(codeGenerator instanceof EjsVueCodeGenerator) {
      codeGenerator.prefix = await this.ejsCodeEncoder.encode()
    }
  }
  
  async applyMethods(openapi: OpenApi, params: ApplyMethodsParamItem[], options?: any) {
    this.ejsCodeEncoder.applyMethods(openapi, params, options)
  }
}

export class EjsVueCodeGenerator extends CodeGenerator implements SinglePageVueCodeGeneratorInterface {
  component: SinglePageVueComponentInterface
  title: string
  constructor(component: SinglePageVueComponentInterface) {
    super("EjsVueCodeGenerator")
    this.component = component
    this.title = "EjsVueCodeGenerator"
  }
  get pages () {
    return [{
      title: this.component.title,
      apiMethods: this.component.apiMethods,
    }]
  }

  async genCode(): Promise<string> {
    await this.encode()
    return await super.genCode()
  }

  async encode() {
    return await this.component.encode(this)
  }

  async updateComponent(component: SinglePageVueComponentInterface) {
    if(component instanceof EjsVueComponent) {
      this.component = component
      await this.encode()
    }
  }

  async applyMethods(openapi: OpenApi, params: ApplyMethodsParamItem[], ejsData?: any, ejsOptions?: any) {
    await this.component.applyMethods(openapi, params.filter((param) => param.page === this.component.title), ejsData, ejsOptions)
  }
}
